package com.jboost.modules.app.service.strategry.xm;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Maps;
import com.google.gson.JsonObject;
import com.jboost.common.util.HttpRestUtils;
import com.jboost.common.util.JSONUtil;
import com.jboost.modules.app.constant.BaseResult;
import com.jboost.modules.app.constant.CustomerDetailInfo;
import com.jboost.modules.app.constant.CustomerInfo;
import com.jboost.modules.app.constant.CustomerOwner;
import com.jboost.modules.app.dto.XMUserReqDto;
import com.jboost.modules.app.dto.XmFieldDto;
import com.jboost.modules.system.entity.SysUserDepart;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.compress.utils.Lists;
import org.springframework.http.HttpHeaders;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service(value = "XmSJQuery")
@Slf4j
public class XmSJQuery extends AbstractXmUser<JsonObject, Boolean> {

    public static void main(String[] args) throws IOException {
        Map<String, XmFieldDto.DataBean> company = getFieldsSelectMap("",select_sj_api);
        XmSJQuery xmUserQuery = new XmSJQuery();
        Map<String, XmFieldDto.DataBean> origin = xmUserQuery.getFieldsEnumMap("origin", xmUserQuery.getHeader("opportunity"));
    }

    @Async
    @Scheduled(cron = "0 0/30 * * * ?")
    public BaseResult<Boolean> invokeStrategy() throws Exception {
        log.info("开始批量查询客户数据");
        String header = getHeader("opportunity");
        List<String> ids = Lists.newArrayList();
        queryAndPush(header, 1, ids);
        List<SysUserDepart> sysUserDeparts = sysUserDepartMapper.selectList(Wrappers.lambdaQuery(SysUserDepart.class).notIn(SysUserDepart::getId, ids));
        for (SysUserDepart sysUserDepart : sysUserDeparts) {
            deleteCustomer(sysUserDepart, header);
        }
        return BaseResult.success();
    }


    public void queryAndPush(String header, Integer index, List<String> ids) throws Exception {
        HashMap<String, Object> paramMap = Maps.newHashMap();
        paramMap.put("start_index", index);
        paramMap.put("count", 20);
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + header);

//        String s = HttpRestUtils.get("https://api-sandbox.xiaoman.cn/v1/company/fields", Maps.newHashMap(), headers);
//        System.out.println(s);
        //String custmorResponse = HttpRestUtils.get(customersUrl, paramMap, headers);
        OkHttpClient cclient = new OkHttpClient();
        Request request1 = new Request.Builder()
                .url(sjUrl+getParams(paramMap)).addHeader("Authorization","Bearer " + header).get()
                .build();
        Response execute1 = cclient.newCall(request1).execute();
        String custmorResponse = execute1.body().string();

    }

    public static String getParams(Map<String, Object> params) {
        StringBuffer sb = new StringBuffer("?");
        if (Objects.nonNull(params)) {
            for (Map.Entry<String, Object> item : params.entrySet()) {
                Object value = item.getValue();
                if (Objects.nonNull(value)) {
                    sb.append("&");
                    sb.append(item.getKey());
                    sb.append("=");
                    sb.append(value);
                }
            }
            return sb.toString();
        } else {
            return "";
        }
    }


    private void updateCustomer(SysUserDepart sysUserDepart, CustomerDetailInfo customerDetailInfo) throws IOException {
        HashMap<String, Object> param = getParam();
        XMUserReqDto xmUserReqDto = buidXMUserReqDto(customerDetailInfo);
        param.put("data", xmUserReqDto);
        param.put("data_id", sysUserDepart.getUserId());
        String post = HttpRestUtils.post(update_api, param, jdyHeaders);
        log.info("表单修改结果{}", post);
    }

    private XMUserReqDto buidXMUserReqDto(CustomerDetailInfo customerDetailInfo) {
        XMUserReqDto xmUserReqDto = new XMUserReqDto();
        CustomerDetailInfo.DataBean data = customerDetailInfo.getData();
        List<CustomerDetailInfo.DataBean.CustomersBean> customers = data.getCustomers();
        //基本资料
        buildXmUserReqDtoBaseData(xmUserReqDto, customerDetailInfo);
        HashMap<String, List<XMUserReqDto.ContactBean>> hashMap = Maps.newHashMap();
        hashMap.put("value",new ArrayList<>());
        xmUserReqDto.setContact(hashMap);
        //运营联系人
        buildXmUserReqDtoData(xmUserReqDto.getContact().get("value"), customers);
        return xmUserReqDto;
    }

    private void buildXmUserReqDtoBaseData(XMUserReqDto xmUserReqDto, CustomerDetailInfo customerDetailInfo) {
        CustomerDetailInfo.DataBean data = customerDetailInfo.getData();
        List<CustomerDetailInfo.DataBean.CompanyBean> company = data.getCompany();
        List<CustomerDetailInfo.DataBean.CompanyBean.FieldsBean> fieldsBeans = company.stream().flatMap(entry -> entry.getFields().stream()).collect(Collectors.toList());
        //fieldsBeans.addAll(customerDetailInfo.getData().getExternal_field_data());
        Map<String, String> fieldMap = fieldsBeans.stream().collect(Collectors.toMap(CustomerDetailInfo.DataBean.CompanyBean.FieldsBean::getId, CustomerDetailInfo.DataBean.CompanyBean.FieldsBean::getValue, (a, b) -> a));
        System.out.println(JSONUtil.toJson(fieldMap));
        xmUserReqDto.setCtreat_time(getParaMap(data.getArchive_time()));
        xmUserReqDto.setAddress(getParaMap(fieldMap.get("address")));
        xmUserReqDto.setCustomer_name(getParaMap(fieldMap.get("name")));
        xmUserReqDto.setCustomer_abbreviation(getParaMap(fieldMap.get("short_name")));
        String country = String.valueOf(getParaMap(fieldMap.get("country")));

        xmUserReqDto.setMonther_land(StringUtils.isBlank(country)?null:getParaMap(filterFh(fieldMap.get("country"))));
        xmUserReqDto.setCustomer_no(getParaMap(customerDetailInfo.getData().getSerial_id()));
        List<XMUserReqDto.LogoBean> logoBeans = new ArrayList<>();
        XMUserReqDto.LogoBean logoBean = new XMUserReqDto.LogoBean();
        logoBean.setUrl(getParaMap(fieldMap.get("homepage")));
        logoBeans.add(logoBean);
        HashMap<String, List<XMUserReqDto.LogoBean>> hashMap = Maps.newHashMap();
        hashMap.put("value",logoBeans);
        xmUserReqDto.setLogo(hashMap);
        xmUserReqDto.setFirst_area(StringUtils.isBlank(String.valueOf(fieldMap.get("4685536191540")))?null:getParaMap(filterFh(fieldMap.get("4685536191540"))));
        xmUserReqDto.setGroup(getParaMap(fieldMap.get("group_id")));
        xmUserReqDto.setCustomer_stage(getParaMap(fieldMap.get("trail_status")));
        xmUserReqDto.setCustomer_nature(getParaMap(fieldMap.get("biz_type")));
        xmUserReqDto.setCustomer_orign(getParaMap(fieldMap.get("origin")));
        xmUserReqDto.setCustomer_attribution(getParaMap(fieldMap.get("")));
        xmUserReqDto.setProduct_customer_label(getParaMap(fieldMap.get("cus_tag")));
        List<CustomerOwner> customerOwners = customerDetailInfo.getData().getOwner();
        //业务员
        List<XMUserReqDto.AffiliatedSalespersonBean> affiliatedSalespersonBeans = new ArrayList<>();
        XMUserReqDto.AffiliatedSalespersonBean affiliatedSalespersonBean = new XMUserReqDto.AffiliatedSalespersonBean();
        String name = "";
        for (CustomerOwner e:
        customerOwners ) {
            affiliatedSalespersonBean = new XMUserReqDto.AffiliatedSalespersonBean();
            affiliatedSalespersonBean.setName(getParaMap(e.getName()));
            affiliatedSalespersonBean.setUsername(getParaMap(e.getNickname()));
            affiliatedSalespersonBeans.add(affiliatedSalespersonBean);
            name = e.getNickname();
        }
        xmUserReqDto.setAffiliated_salesperson(getParaMap(name));
        xmUserReqDto.setCustomer_label(getParaMap(fieldMap.get("cus_tag")));
        xmUserReqDto.setCustomer_nature(getParaMap(fieldMap.get("17995147088")));
        xmUserReqDto.setPhone(getParaMap(fieldMap.get("1990331804234")));
        xmUserReqDto.setHot_selling_series(getParaMap(fieldMap.get("1820018870213")));
        xmUserReqDto.setSurface_treatment(getParaMap(fieldMap.get("1820523514226")));
        xmUserReqDto.setRequired_profile_size(getParaMap(fieldMap.get("1990341612167")));
        xmUserReqDto.setApplication_scenario(getParaMap(fieldMap.get("1820034895295")));
        xmUserReqDto.setCustomer_focus(getParaMap(fieldMap.get("1820036315666")));
        xmUserReqDto.setSearch_fields(getParaMap(fieldMap.get("17385158304")));
        xmUserReqDto.setSearch_keyword_attributes(getParaMap(fieldMap.get("306672013382")));
        xmUserReqDto.setInquiry_type(getParaMap(fieldMap.get("306672013382")));
        xmUserReqDto.setFirst_inquiry_time(getParaMap(fieldMap.get("1575870621271")));
        xmUserReqDto.setBrowse_page(getParaMap(fieldMap.get("3457075506185")));
        xmUserReqDto.setBrowse_time(getParaMap(fieldMap.get("3457081849252")));
        xmUserReqDto.setDrainage_area(getParaMap(fieldMap.get("4685536191540")));
        xmUserReqDto.setAnnual_procurement_amount(getParaMap(fieldMap.get("annual_procurement")));
        xmUserReqDto.setPurchase_intention(getParaMap(fieldMap.get("intention_level")));
        xmUserReqDto.setLading_consignee(getParaMap(fieldMap.get("17995289702")));
        xmUserReqDto.setCompany_remarks(getParaMap(fieldMap.get("remark")));
        xmUserReqDto.setFirst_quest(getParaMap(fieldMap.get("4013377180063")));
        xmUserReqDto.setAnnual_procurement_volume(getParaMap(fieldMap.get("3144298072880")));
        xmUserReqDto.setImport_experience(getParaMap(fieldMap.get("3144323956870")));
        xmUserReqDto.setSales_city(getParaMap(fieldMap.get("1820374615887")));
        xmUserReqDto.setOrder_worry(getParaMap(fieldMap.get("4013469433675")));
        xmUserReqDto.setUser_feed_back(getParaMap(fieldMap.get("4013477508140")));
        xmUserReqDto.setUser_lost_why(getParaMap(fieldMap.get("18387648976")));
        xmUserReqDto.setUser_discount(getParaMap(fieldMap.get("1695297844587")));
        xmUserReqDto.setNew_old_platforms(getParaMap(fieldMap.get("20272197174")));
        xmUserReqDto.setFlow_in(getParaMap(fieldMap.get("22672416156")));
        xmUserReqDto.setProduct_id(getParaMap(fieldMap.get("306665134430")));
        xmUserReqDto.setSettlement_way(getParaMap(fieldMap.get("18364901310")));
        //年龄
        xmUserReqDto.setAge(getParaMap(fieldMap.get("18364901310")));

    }

    private Object filterFh(Object country) {
        String s = country.toString();

        String replaceAll = s.replace("[", "").replace("]","");
        String s1 = replaceAll.replaceAll("\"", "");
        return s1;
    }

    private void buildXmUserReqDtoData(List<XMUserReqDto.ContactBean> contact, List<CustomerDetailInfo.DataBean.CustomersBean> customers) {
        for(CustomerDetailInfo.DataBean.CustomersBean e :customers){
            List<CustomerDetailInfo.DataBean.CustomersBean.ContactBean> contact1 = e.getContact();
            if (CollectionUtil.isNotEmpty(contact1)) {
                for (CustomerDetailInfo.DataBean.CustomersBean.ContactBean b : contact1) {
                    XMUserReqDto.ContactBean contactBean = new XMUserReqDto.ContactBean();
                    contactBean.setContact_name(getParaMap(e.getName()));
                    contactBean.setContcat_email(getParaMap(e.getEmail()));
                    contactBean.setContact_platform(getParaMap(b.getType()));
                    contactBean.setContact_account(getParaMap(b.getValue()));
                    contactBean.setContact_position(getParaMap(e.getPost()));
                    contactBean.setContact_phone(getParaMap(CollectionUtil.isNotEmpty(e.getTel_list()) ? e.getTel_list().get(0).get(0) : null));
                    contact.add(contactBean);
                }
            }else {
                XMUserReqDto.ContactBean contactBean = new XMUserReqDto.ContactBean();
                contactBean.setContact_name(getParaMap(e.getName()));
                contactBean.setContcat_email(getParaMap(e.getEmail()));
                contactBean.setContact_position(getParaMap(e.getPost()));
                contactBean.setContact_phone(getParaMap(CollectionUtil.isNotEmpty(e.getTel_list()) ? e.getTel_list().get(0).get(0) : null));
                contact.add(contactBean);
            }
        };

    }

    private void addCustomer(CustomerDetailInfo customerDetailInfo) throws IOException {
        HashMap<String, Object> param = getParam();
        XMUserReqDto xmUserReqDto = buidXMUserReqDto(customerDetailInfo);
        param.put("data", xmUserReqDto);
        String post = HttpRestUtils.post(add_api, param, jdyHeaders);
        HashMap hashMap = JSONUtil.fromJson(post, HashMap.class);
        log.info("表单新增结果{}", post);
        SysUserDepart userDepart = new SysUserDepart();
        userDepart.setId(customerDetailInfo.getData().getCompany_id() + "");
        userDepart.setUserId(((JSONObject) hashMap.get("data")).getString("_id"));
        userDepart.setDepId(((JSONObject) hashMap.get("data")).getString("customer_serial_number"));
        sysUserDepartMapper.insert(userDepart);

    }

    private void deleteCustomer(SysUserDepart sysUserDepart, String header) throws IOException {
        sysUserDepartMapper.deleteById(sysUserDepart.getId());
        HashMap<String, Object> param = getParam();
        param.put("data_id", sysUserDepart.getUserId());
        String post = HttpRestUtils.post(delete_api, param, jdyHeaders);
        log.info("表单删除结果{}", post);

    }
}
